package com.lei.study;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

/**
 * zookeeper原生客户端
 *
 * @author wulei
 */
public class ZookeeperTest {

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        // 默认的watch
        ZooKeeper client = new ZooKeeper("localhost:2181", 5000, event -> {
            System.out.println("连接事件: " + event);
        });

        // 获取数据
        Stat stat = new Stat();
        byte[] data = client.getData("/lei-test", event -> {
            // 监听器为一次性的
            System.out.println("接收到了回调");
            if (Watcher.Event.EventType.NodeDataChanged.getIntValue() == event.getType().getIntValue()) {
                System.out.println("数据发生了改变");
            }
        }, stat);

        // 使用默认的监听器
        // byte[] data = client.getData("/lei-test", true, stat);

        System.out.println("返回的数据: " + new String(data));
        System.out.println("stat: " + stat);

        // 创建临时顺序节点
        client.create("/zookeeper-e", "1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);

        System.in.read();
    }
}
